<!-- 设备管理-设备运行-设备运行记录页面 -->
<template>
  <div>
    <div v-if="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" inline label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="设备编号/名称">
              <px-input
                v-model="queryParams.value"
                placeholder="请输入设备编号/名称"
                maxlength="50"
                clearable
                @blur="queryParams.value = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <EquipSystemTree
              :className="queryParams.className"
              :systemCode="queryParams.systemCode"
              @changeAllSystemCodes="changeAllSystemCodes"
              @changeSystemCodes="changeSystemCodes"
              @clearSystem="clearSystem"
            />
          </px-col>
          <px-col :span="6">
            <EquipCategorySelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              @changeCategory="changeCategory"
            />
          </px-col>
          <px-col :span="6">
            <EquipTypeSelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              :typeId="queryParams.typeId"
              @changeType="changeType"
            />
          </px-col>
          <px-col :span="6">
            <EquipModelSelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              :typeId="queryParams.typeId"
              :modelId="queryParams.modelId"
              @changeModel="changeModel"
            />
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备运行状态">
              <px-select v-model="queryParams.eqpRunStatus" placeholder="请选择设备运行状态" filterable clearable>
                <px-option v-for="item in eqpRunStatusList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="状态日期">
              <px-date-picker
                v-model="queryParams.timeRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="状态开始日期"
                end-placeholder="状态结束日期"
                unlink-panels
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn-flex">
        <px-button v-has="'ALL_EQUIP_RUNMANAGE_RECORD_ADD'" type="primary" @click="addBtn">新增运行记录</px-button>
        <div>
          <px-button type="primary" @click="queryTable" style="margin-right: 8px">查询</px-button>
          <px-button @click="resetTable" style="margin-right: 8px">重置</px-button>
          <px-button v-has="'ALL_EQUIP_RUNMANAGE_RECORD_BATCH_DOWNLOAD'" type="primary" plain @click="batchDownload">查询并导出</px-button>
        </div>
      </div>
      <px-table :data="tableData" class="equip-table" :height="isFromHandover ? '500px' : 'calc(100vh - 353px)'" border>
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <span v-if="item.eqpRunStatus">
              <px-tag
                v-if="scope.row.eqpRunStatusValue"
                effect="plain"
                :style="{
                  color: `${scope.row.eqpRunStatus === '5' ? '#000' : '#fff'}`,
                  border: 'none',
                  backgroundColor: `${tagBgColorList[scope.row.eqpRunStatus]}`
                }"
              >
                {{ scope.row.eqpRunStatusValue }}
              </px-tag>
              <span v-else>-</span>
            </span>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ALL_EQUIP_RUNMANAGE_RECORD_VIEW'" link icon="Tickets" type="primary" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ALL_EQUIP_RUNMANAGE_RECORD_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ALL_EQUIP_RUNMANAGE_RECORD_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :class="isFromHandover ? 'handover-pagination' : 'equip-table-pagination'"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddEquipDetail
      :isMain="isMain"
      :isView="isView"
      :drawerType="drawerType"
      :rowData="rowData"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
      :planId="planId"
    />
    <!-- 查看页面 -->
    <ViewEquipDetail :isMain="isMain" :isView="isView" :drawerType="drawerType" :rowData="rowData" @backMainPage="backMainPage" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_RUNMANAGE_RECORD"
});
import { onActivated, onMounted, reactive, toRefs, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import AddEquipDetail from "./components/AddEquipDetail.vue";
import ViewEquipDetail from "./components/ViewEquipDetail.vue";
import { queryDictData } from "@/api/common";
import { deleteRunRecord, queryRunRecord } from "@/api/equip/runManage";

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "eqpId", label: "设备编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    { prop: "eqpName", label: "设备名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "eqpRunStatus", label: "设备运行状态", minWidth: "120", showOverflowTooltip: true, eqpRunStatus: true },
    { prop: "downCauseName", label: "状态原因", minWidth: "120", showOverflowTooltip: true },
    { prop: "downTypeName", label: "状态类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "startTime", label: "状态开始时间", minWidth: "160", showOverflowTooltip: true },
    { prop: "endTime", label: "状态结束时间", minWidth: "160", showOverflowTooltip: true },
    { prop: "runTimes", label: "状态时长", minWidth: "140", showOverflowTooltip: true },
    // { prop: "reportTypeName", label: "来源", minWidth: "150", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "80", showOverflowTooltip: true },
    { prop: "systemName", label: "系统", minWidth: "130", showOverflowTooltip: true }
  ],
  tableData: [], // 列表数据
  total: 0, // 列表数量
  eqpRunStatusList: [], // 设备运行状态下拉框
  rowData: {},
  drawerType: "add", // 默认新增
  isFromHandover: false,
  systemCodes: [],
  planId: 0,
  isFirstLoad: true
});

const {
  isMain,
  isView,
  queryParams,
  tableColumns,
  tableData,
  total,
  eqpRunStatusList,
  rowData,
  drawerType,
  isFromHandover,
  systemCodes,
  planId,
  isFirstLoad
} = toRefs(state);

const tagBgColorList = {
  1: "#10B981", // 运行
  2: "#9254DE", // 故障（报警且停机）/异常停机
  3: "#F59E0B", // 带病（报警且运行）/异常
  4: "#909399", // 离线
  5: "#efefef" // 停机
};

onActivated(async () => {
  if (!isFirstLoad.value) {
    getPage();
  }
});
onMounted(async () => {
  getPage();
});

// 获取首页数据
const getPage = async () => {
  isFromHandover.value = false;
  // 来源于交接班，table高度有区别
  if (route?.query && route?.query?.source === "handover") {
    isFromHandover.value = true;
  }
  if (route?.query && route?.query?.className) {
    queryParams.value.className = route?.query?.className;
  }
  if (route?.query && route?.query?.eqpId) {
    queryParams.value.value = route?.query?.eqpId;
  }
  if (route?.query && route?.query?.eqpRunStatus) {
    queryParams.value.eqpRunStatus = route?.query?.eqpRunStatus;
  }
  if (route?.query && route?.query?.planId) {
    isMain.value = false;
    isView.value = false;
    planId.value = route?.query?.planId;
    drawerType.value = "add";
  }
  await querySelectList();
  if (route?.query && route?.query?.eqpRunStatusName) {
    queryParams.value.eqpRunStatus = eqpRunStatusList.value.find(s => s.name === route?.query?.eqpRunStatusName)?.value;
  }
  queryTable();
};

// 搜索查询条件下拉框
const querySelectList = async () => {
  eqpRunStatusList.value = await queryDictData({ typeCode: "EQP_RUN_STATUS" });
};
// 查询列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  params.systemCodes = systemCodes.value;
  params.startTime = queryParams.value.timeRange ? queryParams.value.timeRange[0] + " 00:00:00" : "";
  params.endTime = queryParams.value.timeRange ? queryParams.value.timeRange[1] + " 23:59:59" : "";
  const res = await queryRunRecord(params);
  tableData.value = res?.data || [];
  total.value = res?.total;
  isFirstLoad.value = false;
};
// 重置筛选条件和列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  queryTable();
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  // if (route?.query && route?.query?.planId) {
  //   router.push({ query: {} });
  // }
  querySelectList();
  queryTable();
};
// 查看设备
const handleView = (row: any) => {
  drawerType.value = "view";
  planId.value = 0;
  rowData.value = row;
  isMain.value = false;
  isView.value = true;
};
// 新增运行记录-显示弹窗
const addBtn = () => {
  drawerType.value = "add";
  planId.value = 0;
  isMain.value = false;
  isView.value = false;
};
// 编辑运行记录-显示弹窗
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  planId.value = 0;
  rowData.value = row;
  isMain.value = false;
  isView.value = false;
};
// 删除运行记录
const handleDelete = async (row: any) => {
  PxMessageBox.confirm("要删除当前设备运行记录吗？", "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteRunRecord({
        id: row.id
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  queryParams.value.categoryId = val;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  queryParams.value.categoryId = val2;
  queryParams.value.typeId = val;
  queryParams.value.modelId = null;
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  queryParams.value.categoryId = val2;
  queryParams.value.typeId = val3;
  queryParams.value.modelId = val;
};
// 批量下载
const batchDownload = async () => {
  await queryTable();
  const params = {
    value: queryParams.value.value,
    className: queryParams.value.className,
    systemCodes: systemCodes.value,
    categoryId: queryParams.value.categoryId,
    typeId: queryParams.value.typeId,
    modelId: queryParams.value.modelId,
    eqpRunStatus: queryParams.value.eqpRunStatus,
    startTime: queryParams.value.timeRange ? queryParams.value.timeRange[0] + " 00:00:00" : "",
    endTime: queryParams.value.timeRange ? queryParams.value.timeRange[1] + " 23:59:59" : ""
  };
  proxy.download("post", "/digitaltwins/api/v1/eqp/runRecord/exportList", params, "设备运行记录.xlsx");
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-wrap-common {
  .handover-pagination {
    position: relative;
    right: -16px;
    bottom: auto;
    width: 100%;
    margin-top: 12px;
  }
}
</style>
